<?php

namespace App\Common\Listener;

use think\event\LogWrite;

/**
 * 日志写入请求ID
 */
class LogWriteRequestIdListener
{
    private static string $requestId = '';

    public function handle(LogWrite $logWrite): void
    {
        $requestId = $this->getRequestId();

        foreach ($logWrite->log as &$messages) {
            $messages = array_map(fn($message) => sprintf("<%s> %s", $requestId, $message), $messages);
        }
    }

    /**
     * @return string
     */
    private function getRequestId(): string
    {
        if (!self::$requestId) {
            self::$requestId = substr(md5(microtime()), 0, 10);
        }

        return self::$requestId;
    }
}